package com.utils;

import android.content.Context;
import android.os.Environment;

import java.io.FileOutputStream;
import java.util.Calendar;

/**
 * Created by happy_000 on 2014/11/14.
 */
public class ErrorLog {
    public static boolean isLock=false;
    public static void saveError(Context context,String str,boolean isClear){
        String mFileName = Environment.getExternalStorageDirectory() + "/error.txt";
        if (isLock){
            writeFileSdcard(mFileName,str);
        }else {
            if (isClear){
                writeFileSdcardWithClear(mFileName,str);
            }
            else {

                writeFileSdcard(mFileName,str);
                isLock=true;
                ToastUtil.toastShortly(context,"错误日志已保存在"+mFileName);
            }
        }
        }
    public static void saveRunTimeError(Context context,String str){
        String mFileName =Environment.getExternalStorageDirectory() + "/runtiome_error.txt";
                writeFileSdcard(mFileName,str);
    }

    private   static void writeFileSdcard(String fileName,String str){
        Calendar calendar=Calendar.getInstance();
        str="\\n"+calendar.get(calendar.YEAR)+"-"+calendar.get(calendar.MONTH)+"-"+calendar.get(calendar.DAY_OF_MONTH)+
                calendar.get(calendar.HOUR_OF_DAY)+":"+calendar.get(calendar.MINUTE)+"返回数据:"+str;
        try{

            //FileOutputStream fout = openFileOutput(fileName, MODE_PRIVATE);

            FileOutputStream fout = new FileOutputStream(fileName,true);

            byte [] bytes = str.getBytes();

            fout.write(bytes);

            fout.close();

        }

        catch(Exception e){

            e.printStackTrace();

        }


    }
    private   static void writeFileSdcardWithClear(String fileName,String message){
        Calendar calendar=Calendar.getInstance();
        message="\\n"+calendar.get(calendar.YEAR)+"-"+calendar.get(calendar.MONTH)+"-"+calendar.get(calendar.DAY_OF_MONTH)+
                calendar.get(calendar.HOUR_OF_DAY)+":"+calendar.get(calendar.MINUTE)+"请求参数:"+message;
        try{

            //FileOutputStream fout = openFileOutput(fileName, MODE_PRIVATE);

            FileOutputStream fout = new FileOutputStream(fileName,false);

            byte [] bytes = message.getBytes();

            fout.write(bytes);

            fout.close();

        }

        catch(Exception e){

            e.printStackTrace();

        }

    }
}
